<template>
  <div v-if="showAddCameraDialog" class="add-camera-modal" @click="$emit('cancel')">
    <div class="add-camera-container" @click.stop>
      <div class="add-camera-header">
        <h3>{{ isEditingCamera ? '编辑摄像头点位' : '新增摄像头点位' }}</h3>
        <button @click="$emit('cancel')" class="close-btn">×</button>
      </div>
      <div class="add-camera-content">
        <div class="position-info" v-if="selectedPosition && selectedPosition.longitude !== undefined">
          <div class="info-row">
            <span class="label">选择位置:</span>
            <span class="value">
              经度: {{ selectedPosition.longitude?.toFixed(6) || '0.000000' }}, 
              纬度: {{ selectedPosition.latitude?.toFixed(6) || '0.000000' }}
            </span>
          </div>
          <div class="info-row">
            <span class="label">高度:</span>
            <span class="value">{{ selectedPosition.height?.toFixed(2) || '0.00' }}m</span>
          </div>
        </div>
        
        <div class="position-tip" v-if="!selectedPosition">
          <div class="tip-icon">📍</div>
          <div class="tip-text">
            <strong>请在3D场景中点击选择摄像头安装位置</strong>
            <p>点击地面或建筑物表面来确定摄像头的安装坐标</p>
          </div>
        </div>
        
        <div class="camera-form">
          <div class="form-row">
            <label>WVP设备选择 *</label>
            <select 
              v-model="selectedDeviceId" 
              class="form-select"
              @change="onDeviceChange"
            >
              <option value="">请选择WVP设备</option>
              <option 
                v-for="device in wvpDevices" 
                :key="device.deviceId" 
                :value="device.deviceId"
              >
                {{ device.name }} ({{ device.deviceId }})
              </option>
            </select>
          </div>
          
          <div class="form-row" v-if="selectedDeviceId">
            <label>设备通道 *</label>
            <select 
              v-model="selectedChannelId" 
              class="form-select"
              @change="onChannelChange"
              :disabled="loading"
            >
              <option value="">{{ loading ? '正在加载通道...' : '请选择设备通道' }}</option>
              <option 
                v-for="channel in deviceChannels" 
                :key="channel.channelId || channel.deviceId || channel.id" 
                :value="channel.channelId || channel.deviceId || channel.id"
              >
                {{ channel.name || channel.channelId || channel.deviceId }} ({{ channel.channelId || channel.deviceId || channel.id }})
              </option>
              <option v-if="deviceChannels.length === 0 && !loading" value="default">
                使用设备默认通道
              </option>
            </select>
            <div v-if="deviceChannels.length === 0 && !loading" class="form-message warning">
              该设备没有可用通道，将使用设备默认配置
            </div>
          </div>
          
          <div class="form-row">
            <label>设备名称 *</label>
            <input 
              v-model="newCameraForm.name" 
              type="text" 
              placeholder="请输入设备名称"
              class="form-input"
              :class="{ 'error': !newCameraForm?.name?.trim() && newCameraForm?.name !== '' }"
              @blur="$emit('checkName')"
            />
            <div v-if="nameCheckMessage" class="form-message" :class="nameCheckMessage.type">
              {{ nameCheckMessage.text }}
            </div>
          </div>
          
          <div class="form-row">
            <label>安装位置</label>
            <input 
              v-model="newCameraForm.location" 
              type="text" 
              placeholder="请输入安装位置"
              class="form-input"
            />
          </div>
          
          <div class="form-row">
            <label>RTSP地址 *</label>
            <input 
              v-model="newCameraForm.rtsp_url" 
              type="text" 
              placeholder="rtsp://192.168.1.100:554/stream1"
              class="form-input"
              :class="{ 'error': !newCameraForm?.rtsp_url?.trim() && newCameraForm?.rtsp_url !== '' }"
            />
          </div>
          
          <div class="form-row-group">
            <div class="form-row half">
              <label>WVP设备ID</label>
              <input 
                v-model="newCameraForm.wvp_device_id" 
                type="text" 
                placeholder="WVP-Pro设备ID"
                class="form-input"
              />
            </div>
            <div class="form-row half">
              <label>WVP通道ID</label>
              <input 
                v-model="newCameraForm.wvp_channel_id" 
                type="text" 
                placeholder="WVP-Pro通道ID"
                class="form-input"
              />
            </div>
          </div>
          
          <div class="form-row">
            <label>设备描述</label>
            <textarea 
              v-model="newCameraForm.description" 
              placeholder="请输入设备描述信息"
              class="form-textarea"
              rows="3"
            ></textarea>
          </div>
          
          <div class="form-row">
            <label class="checkbox-label">
              <input 
                v-model="newCameraForm.ai_enabled" 
                type="checkbox"
                class="form-checkbox"
              />
              启用AI分析
            </label>
          </div>
        </div>
        
        <div class="add-camera-actions">
          <button @click="$emit('cancel')" class="action-btn cancel-btn">
            取消
          </button>
          <button @click="$emit('confirm')" class="action-btn confirm-btn" :disabled="!canSaveCamera">
            {{ isAddingCamera ? (isEditingCamera ? '更新中...' : '添加中...') : (isEditingCamera ? '确认更新' : '确认添加') }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { listDevice, listDeviceChannel } from '@/api/python-camera'
import { listDevice as listWvpDevice, listDeviceChannel as listWvpDeviceChannel } from '@/api/wvp/device'

// 定义props
const props = defineProps({
  showAddCameraDialog: Boolean,
  selectedPosition: Object,
  newCameraForm: Object,
  nameCheckMessage: Object,
  canSaveCamera: Boolean,
  isAddingCamera: Boolean,
  isEditingCamera: Boolean
})

// 定义事件
const emit = defineEmits(['cancel', 'confirm', 'checkName', 'updateForm'])

// WVP设备相关数据
const wvpDevices = ref([])
const deviceChannels = ref([])
const selectedDeviceId = ref('')
const selectedChannelId = ref('')
const loading = ref(false)

// 获取WVP设备列表
const loadWvpDevices = async () => {
  try {
    loading.value = true
    console.log('正在获取设备列表...')
    
    // 首先尝试从Python后端获取设备列表
    let response = await listDevice({
      pageNum: 1,
      pageSize: 100 // 获取所有设备
    })
    
    console.log('Python后端设备API响应:', response)
    
    // 检查Python后端是否有数据
    let devices = []
    if (response && (response.code === 200 || response.code === 0)) {
      if (response.rows && Array.isArray(response.rows)) {
        devices = response.rows
      } else if (response.data && response.data.rows) {
        devices = response.data.rows
      } else if (response.data && response.data.list) {
        devices = response.data.list
      } else if (Array.isArray(response.data)) {
        devices = response.data
      }
    }
    
    // 如果Python后端没有数据，回退到WVP API
    if (devices.length === 0) {
      console.log('Python后端没有设备数据，回退到WVP API...')
      try {
        response = await listWvpDevice({
          pageNum: 1,
          pageSize: 100
        })
        
        console.log('WVP设备API响应:', response)
        
        if (response && (response.code === 200 || response.code === 0)) {
          if (response.rows && Array.isArray(response.rows)) {
            devices = response.rows
          } else if (response.data && response.data.rows) {
            devices = response.data.rows
          } else if (response.data && response.data.list) {
            devices = response.data.list
          } else if (Array.isArray(response.data)) {
            devices = response.data
          }
          console.log('使用WVP API获取到设备:', devices.length, '个')
        }
      } catch (wvpError) {
        console.error('WVP API也失败了:', wvpError)
      }
    } else {
      console.log('使用Python后端获取到设备:', devices.length, '个')
    }
    
    wvpDevices.value = devices
    console.log('最终设备列表:', wvpDevices.value)
    
  } catch (error) {
    console.error('获取设备列表失败:', error)
    // 如果Python后端完全失败，尝试WVP API作为备用
    try {
      console.log('Python后端失败，尝试WVP API作为备用...')
      const fallbackResponse = await listWvpDevice({
        pageNum: 1,
        pageSize: 100
      })
      
      if (fallbackResponse && (fallbackResponse.code === 200 || fallbackResponse.code === 0)) {
        let fallbackDevices = []
        if (fallbackResponse.rows && Array.isArray(fallbackResponse.rows)) {
          fallbackDevices = fallbackResponse.rows
        }
        wvpDevices.value = fallbackDevices
        console.log('备用WVP API获取到设备:', fallbackDevices.length, '个')
      }
    } catch (fallbackError) {
      console.error('备用WVP API也失败了:', fallbackError)
    }
  } finally {
    loading.value = false
  }
}

// 获取设备通道列表
const loadDeviceChannels = async (deviceId) => {
  try {
    loading.value = true
    console.log('正在获取设备通道:', deviceId)
    
    // 首先尝试从Python后端获取通道列表
    let response = await listDeviceChannel({
      deviceId: deviceId,
      pageNum: 1,
      pageSize: 100
    })
    
    console.log('Python后端通道API响应:', response)
    
    let channels = []
    if (response && (response.code === 200 || response.code === 0)) {
      if (response.rows && Array.isArray(response.rows)) {
        channels = response.rows
      } else if (response.data && response.data.rows) {
        channels = response.data.rows
      } else if (response.data && response.data.list) {
        channels = response.data.list
      } else if (Array.isArray(response.data)) {
        channels = response.data
      }
    }
    
    // 如果Python后端没有通道数据，回退到WVP API
    if (channels.length === 0) {
      console.log('Python后端没有通道数据，回退到WVP API...')
      try {
        response = await listWvpDeviceChannel({
          deviceId: deviceId,
          pageNum: 1,
          pageSize: 100
        })
        
        console.log('WVP通道API响应:', response)
        
        if (response && (response.code === 200 || response.code === 0)) {
          if (response.rows && Array.isArray(response.rows)) {
            channels = response.rows
          } else if (response.data && response.data.rows) {
            channels = response.data.rows
          } else if (response.data && response.data.list) {
            channels = response.data.list
          } else if (Array.isArray(response.data)) {
            channels = response.data
          }
          console.log('使用WVP API获取到通道:', channels.length, '个')
        }
      } catch (wvpError) {
        console.error('WVP通道API也失败了:', wvpError)
      }
    } else {
      console.log('使用Python后端获取到通道:', channels.length, '个')
    }
    
    deviceChannels.value = channels
    console.log('最终通道列表:', deviceChannels.value)
    
  } catch (error) {
    console.error('获取设备通道列表失败:', error)
    // 如果Python后端完全失败，尝试WVP API作为备用
    try {
      console.log('Python后端失败，尝试WVP API作为备用...')
      const fallbackResponse = await listWvpDeviceChannel({
        deviceId: deviceId,
        pageNum: 1,
        pageSize: 100
      })
      
      if (fallbackResponse && (fallbackResponse.code === 200 || fallbackResponse.code === 0)) {
        let fallbackChannels = []
        if (fallbackResponse.rows && Array.isArray(fallbackResponse.rows)) {
          fallbackChannels = fallbackResponse.rows
        }
        deviceChannels.value = fallbackChannels
        console.log('备用WVP API获取到通道:', fallbackChannels.length, '个')
      }
    } catch (fallbackError) {
      console.error('备用WVP API也失败了:', fallbackError)
      deviceChannels.value = []
    }
  } finally {
    loading.value = false
  }
}

// 设备选择变化
const onDeviceChange = () => {
  selectedChannelId.value = ''
  deviceChannels.value = []
  
  if (selectedDeviceId.value) {
    console.log('选择设备:', selectedDeviceId.value)
    loadDeviceChannels(selectedDeviceId.value)
    
    // 立即填充设备ID
    emit('updateForm', {
      wvp_device_id: selectedDeviceId.value,
      wvp_channel_id: '',
      rtsp_url: ''
    })
  } else {
    // 清空相关字段
    emit('updateForm', {
      rtsp_url: '',
      wvp_device_id: '',
      wvp_channel_id: ''
    })
  }
}

// 通道选择变化
const onChannelChange = async () => {
  if (selectedChannelId.value && selectedDeviceId.value) {
    const selectedDevice = wvpDevices.value.find(device => device.deviceId === selectedDeviceId.value)
    
    // 处理默认通道的情况
    let selectedChannel = null
    if (selectedChannelId.value === 'default') {
      // 使用设备作为默认通道
      selectedChannel = {
        channelId: selectedDeviceId.value,
        name: selectedDevice?.name || selectedDeviceId.value,
        deviceId: selectedDeviceId.value
      }
      console.log('使用设备默认通道:', selectedChannel)
    } else {
      selectedChannel = deviceChannels.value.find(
        channel => (channel.channelId || channel.deviceId || channel.id) === selectedChannelId.value
      )
    }
    
    if (selectedDevice && selectedChannel) {
      console.log('选择的设备信息:', selectedDevice)
      console.log('选择的通道信息:', selectedChannel)
      
      const actualChannelId = selectedChannelId.value === 'default' ? selectedDeviceId.value : selectedChannelId.value
      
      const updateData = {
        wvp_device_id: selectedDeviceId.value,
        wvp_channel_id: actualChannelId
      }
      
      // 在编辑模式下，总是更新设备名称以反映新选择的通道
      if (props.isEditingCamera) {
        // 优先使用通道名称，如果没有则使用设备名称+通道ID
        let deviceName = selectedChannel.name || selectedChannel.channelId || selectedChannel.deviceId
        if (!deviceName || deviceName === actualChannelId) {
          deviceName = `${selectedDevice.name || selectedDevice.deviceId}_${actualChannelId}`
        }
        updateData.name = deviceName
      } else if (!props.newCameraForm?.name?.trim()) {
        // 新增模式下，只在名称为空时自动填充
        let deviceName = selectedChannel.name || selectedChannel.channelId || selectedChannel.deviceId
        if (!deviceName || deviceName === actualChannelId) {
          deviceName = `${selectedDevice.name || selectedDevice.deviceId}_${actualChannelId}`
        }
        updateData.name = deviceName
      }
      
      // 构建播放地址
      try {
        let rtspUrl = ''
        
        // 方法1: 如果通道有直接的RTSP地址
        if (selectedChannel.rtspUrl || selectedChannel.rtsp_url) {
          rtspUrl = selectedChannel.rtspUrl || selectedChannel.rtsp_url
          console.log('使用通道直接RTSP地址:', rtspUrl)
        }
        // 方法2: 构建WVP标准播放地址
        else {
          const streamId = `${selectedDeviceId.value}_${actualChannelId}`
          
          // WVP服务器配置
          const wvpHost = window.location.hostname || 'localhost'
          const rtspPort = '554' // WVP RTSP端口
          const httpPort = '18080' // WVP HTTP端口
          
          // 构建多种可能的播放地址
          const possibleUrls = [
            // WVP标准RTSP地址（推荐，根据提供的格式）
            `rtsp://${wvpHost}:${rtspPort}/rtp/${streamId}`,
            // WVP HTTP-FLV流地址
            `http://${wvpHost}:${httpPort}/rtp/${streamId}.flv`,
            // WVP HLS流地址
            `http://${wvpHost}:${httpPort}/rtp/${streamId}.m3u8`,
            // WVP WebRTC地址
            `http://${wvpHost}:${httpPort}/rtp/${streamId}/webrtc`
          ]
          
          // 优先使用标准RTSP格式，符合WVP规范
          rtspUrl = possibleUrls[0]
          console.log('构建的WVP RTSP地址:', rtspUrl)
          console.log('其他可选地址:', possibleUrls.slice(1))
        }
        
        if (rtspUrl) {
          updateData.rtsp_url = rtspUrl
        } else {
          console.warn('无法构建播放地址，设备信息不完整')
          // 提供一个WVP标准RTSP模板
          const streamId = `${selectedDeviceId.value}_${actualChannelId}`
          const wvpHost = window.location.hostname || 'localhost'
          updateData.rtsp_url = `rtsp://${wvpHost}:554/rtp/${streamId}`
        }
        
      } catch (error) {
        console.error('构建播放地址失败:', error)
        const streamId = `${selectedDeviceId.value}_${actualChannelId}`
        const wvpHost = window.location.hostname || 'localhost'
        updateData.rtsp_url = `rtsp://${wvpHost}:554/rtp/${streamId}`
      }
      
      console.log('自动填充的表单数据:', updateData)
      
      // 通过emit更新表单数据
      emit('updateForm', updateData)
    }
  } else {
    // 清空通道相关字段，但保留设备ID
    emit('updateForm', {
      wvp_channel_id: '',
      rtsp_url: ''
    })
  }
}

// 监听对话框显示状态，加载设备列表
watch(() => props.showAddCameraDialog, async (newVal) => {
  if (newVal) {
    await loadWvpDevices()
    
    // 如果是编辑模式，设置选中的设备和通道
    if (props.isEditingCamera && props.newCameraForm) {
      selectedDeviceId.value = props.newCameraForm.wvp_device_id || ''
      
      if (selectedDeviceId.value) {
        // 加载设备通道
        await loadDeviceChannels(selectedDeviceId.value)
        selectedChannelId.value = props.newCameraForm.wvp_channel_id || ''
      }
    } else {
      // 新增模式，重置选择
      selectedDeviceId.value = ''
      selectedChannelId.value = ''
      deviceChannels.value = []
    }
  }
})

// 监听选择位置变化，自动填充安装位置
watch(() => props.selectedPosition, (newPosition) => {
  if (newPosition) {
    const locationText = `经度: ${newPosition.longitude?.toFixed(6)}, 纬度: ${newPosition.latitude?.toFixed(6)}, 高度: ${newPosition.height?.toFixed(2)}m`
    emit('updateForm', { location: locationText })
  }
}, { immediate: true })

// 组件挂载时加载设备列表
onMounted(() => {
  if (props.showAddCameraDialog) {
    loadWvpDevices()
  }
})
</script>

<style lang="scss" scoped>
.add-camera-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 3000;
}

.add-camera-container {
  background: white;
  border-radius: 12px;
  width: 90vw;
  max-width: 600px;
  max-height: 90vh;
  overflow: hidden;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
}

.add-camera-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;

  h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: #2c3e50;
  }

  .close-btn {
    background: none;
    border: none;
    font-size: 24px;
    cursor: pointer;
    color: #6c757d;
    padding: 4px;
    border-radius: 4px;
    
    &:hover {
      background: #e9ecef;
      color: #495057;
    }
  }
}

.add-camera-content {
  padding: 24px;
  max-height: calc(90vh - 140px);
  overflow-y: auto;
}

.position-info {
  background: #e3f2fd;
  border: 1px solid #2196f3;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 20px;

  .info-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;

    &:last-child {
      margin-bottom: 0;
    }

    .label {
      font-weight: 600;
      color: #1976d2;
      min-width: 80px;
    }

    .value {
      color: #0d47a1;
      font-family: monospace;
      font-size: 14px;
    }
  }
}

.position-tip {
  background: #fef3c7;
  border: 1px solid #f59e0b;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 20px;
  display: flex;
  align-items: flex-start;
  gap: 12px;

  .tip-icon {
    font-size: 24px;
    flex-shrink: 0;
  }

  .tip-text {
    flex: 1;

    strong {
      color: #92400e;
      display: block;
      margin-bottom: 4px;
    }

    p {
      margin: 0;
      color: #b45309;
      font-size: 13px;
      line-height: 1.4;
    }
  }
}

.camera-form {
  .form-row {
    margin-bottom: 16px;

    label {
      display: block;
      margin-bottom: 6px;
      font-weight: 600;
      color: #374151;
      font-size: 14px;
    }

    .form-input, .form-select {
      width: 100%;
      padding: 10px 12px;
      border: 1px solid #d1d5db;
      border-radius: 6px;
      font-size: 14px;
      transition: border-color 0.2s;
      background: white;

      &:focus {
        outline: none;
        border-color: #3b82f6;
        box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
      }

      &::placeholder {
        color: #9ca3af;
      }

      &.error {
        border-color: #ef4444;
        box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.1);
      }
    }
    
    .form-select {
      cursor: pointer;
      
      option {
        padding: 8px;
      }
    }

    .form-message {
      margin-top: 4px;
      font-size: 12px;
      
      &.error {
        color: #ef4444;
      }
      
      &.success {
        color: #10b981;
      }
      
      &.warning {
        color: #f59e0b;
      }
    }

    .form-textarea {
      width: 100%;
      padding: 10px 12px;
      border: 1px solid #d1d5db;
      border-radius: 6px;
      font-size: 14px;
      resize: vertical;
      min-height: 80px;
      font-family: inherit;
      transition: border-color 0.2s;

      &:focus {
        outline: none;
        border-color: #3b82f6;
        box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
      }

      &::placeholder {
        color: #9ca3af;
      }
    }

    .checkbox-label {
      display: flex;
      align-items: center;
      cursor: pointer;
      font-weight: normal;

      .form-checkbox {
        margin-right: 8px;
        width: 16px;
        height: 16px;
      }
    }
  }

  .form-row-group {
    display: flex;
    gap: 16px;
    margin-bottom: 16px;

    .form-row {
      margin-bottom: 0;

      &.half {
        flex: 1;
      }
    }
  }
}

.add-camera-actions {
  display: flex;
  gap: 12px;
  margin-top: 24px;
  padding-top: 20px;
  border-top: 1px solid #e5e7eb;

  .action-btn {
    flex: 1;
    padding: 12px 24px;
    border: none;
    border-radius: 8px;
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s;

    &.cancel-btn {
      background: #f3f4f6;
      color: #374151;
      
      &:hover {
        background: #e5e7eb;
      }
    }

    &.confirm-btn {
      background: #10b981;
      color: white;
      
      &:hover:not(:disabled) {
        background: #059669;
      }

      &:disabled {
        background: #d1d5db;
        color: #9ca3af;
        cursor: not-allowed;
      }
    }
  }
}
</style>